/**
 * Theme: Minton Admin Template
 * Author: Coderthemes
 * Component: Editable
 * <p>
 *     1、实现可编辑表格；
 *     2、实现产品添加；
 *     3，实现产品修改；
 *     4，实现产品删除
 * </p>
 *
 */


var tables;
var selectVal = $("#selectadd").html();
var statusVal = $("#statusadd").html();
(function( $ ) {
    $(".select2").select2();
    'use strict';

    var EditableTable = {

        options: {
            addButton: '#addToTable',
            table: '#datatable-editable',
            dialog: {
                wrapper: '#dialog',
                cancelButton: '#dialogCancel',
                confirmButton: '#dialogConfirm',
            }
        },

        initialize: function() {
            this
                .setVars()
                .build()
                .events();
        },

        setVars: function() {
            this.$table				= $( this.options.table );
            this.$addButton			= $( this.options.addButton );

            // dialog
            this.dialog				= {};
            this.dialog.$wrapper	= $( this.options.dialog.wrapper );
            this.dialog.$cancel		= $( this.options.dialog.cancelButton );
            this.dialog.$confirm	= $( this.options.dialog.confirmButton );

            return this;
        },

        build: function() {
            tables=this.datatable = this.$table.DataTable({
                "iDisplayLength": 50,
                "sDom": "t<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
                "language": {
                    "decimal":        "",
                    "emptyTable":     "没有数据",
                    "info":           "从 _START_ 条到 _END_ 条共 _TOTAL_ 条",
                    "infoEmpty":      "从 0 到 0 页共 0 页",
                    "infoFiltered":   "(总共 _MAX_ 条)",
                    "infoPostFix":    "",
                    "thousands":      ",",
                    "lengthMenu":     "显示 _MENU_ 页",
                    "loadingRecords": "Loading...",
                    "processing":     "Processing...",
                    "search":         "搜索:",
                    "zeroRecords":    "No matching records found",
                    "paginate": {
                        "first":      "第一页",
                        "last":       "最后一页",
                        "next":       "下一页",
                        "previous":   "上一页"
                    },
                },
                "ordering": false,
                aoColumns: [
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    { "bSortable": false }
                ]
            });

            window.dt = this.datatable;

            return this;
        },


        events: function() {
            var _self = this;

            this.$table
                .on('click', 'a.save-row', function( e ) {
                    e.preventDefault();
                    _self.rowSave( $(this).closest( 'tr' ) );
                })
                .on('click', 'a.cancel-row', function( e ) {
                    e.preventDefault();

                    _self.rowCancel( $(this).closest( 'tr' ) );
                })
                .on('click', 'a.edit-row', function( e ) {
                    e.preventDefault();
                    _self.rowEdit( $(this).closest( 'tr' ) ,"");
                })
                .on( 'click', 'a.remove-row', function( e ) {
                    e.preventDefault();

                    var $row = $(this).closest( 'tr' );

                    _self.rowRemove( $row,'' );
                });

            this.$addButton.on( 'click', function(e) {
                e.preventDefault();

                _self.rowAdd();
            });

            this.dialog.$cancel.on( 'click', function( e ) {
                e.preventDefault();
                $.magnificPopup.close();
            });

            return this;
        },

        // ==========================================================================================
        // ROW FUNCTIONS
        // ==========================================================================================
        rowAdd: function() {
            this.$addButton.attr({ 'disabled': 'disabled' });

            var actions,
                data,
                $row;
            var discount = $("#discount").val();
            actions = [
                '<a href="#" class="hidden on-editing save-row m-r-10"><i class="fa fa-save fa-18"></i></a>',
                '<a href="#" class="hidden on-editing cancel-row m-r-10"><i class="fa fa-times fa-18"></i></a>',
                '<a href="#" class="on-default edit-row m-r-10"><i class="fa fa-pencil fa-18"></i></a>',
                '<a href="#" class="on-default remove-row m-r-10"><i class="fa fa-trash-o fa-18"></i></a>'
            ].join(' ');

            data = this.datatable.row.add([ selectVal,'','','',discount,'','',statusVal,'', actions ]);
            $row = this.datatable.row( data[0] ).nodes().to$();
            $row.find( 'td' ).eq(3).addClass( 'hidden' );
            $row.find( 'td' ).eq(6).addClass( 'hidden' );
            $row.find( 'td' ).eq(8).addClass( 'hidden' );
            $row
                .addClass( 'adding' )
                .find( 'td:last' )
                .addClass( 'actions' );

            this.rowEdit( $row ,"aa");

            this.datatable.order([0,'asc']).draw(); // always show fields
        },

        rowCancel: function( $row ) {
            var _self = this,
                $actions,
                i,
                data;
            if ( $row.hasClass('adding')) {
                this.rowRemove( $row );
            } else {

                data = this.datatable.row( $row.get(0) ).data();
                this.datatable.row( $row.get(0) ).data( data );

                $actions = $row.find('td.actions');
                if ( $actions.get(0) ) {
                    this.rowSetActionsDefault( $row );
                }

                this.datatable.draw();
            }
        },

        rowEdit: function( $row,aa ) {
            var _self = this,
                data;

            data = this.datatable.row( $row.get(0) ).data();
            $row.children( 'td' ).each(function( i ) {
                var $this = $( this );
                if ( $this.hasClass('actions') ) {
                    _self.rowSetActionsEditing( $row );
                } else {
                    if(i == 0){
                        // _self.rowSetActionsEditing( $row );
                        $this.html(selectVal);
                        $row.find("select").eq(0).val(data[6]);//下拉默认选中赋值
                    }else if(i==3){
                        //生成唯一id
                        if(!aa){
                            $this.html( '<input type="text" class="form-control input-block" value="' + data[i] + '"/>' );
                        }else {
                            var mth = (Math.random()*1000000000000+"").substr(0,11);
                            $this.html( '<input type="hidden" class="form-control input-block" value="' + mth + '"/>' );
                        }
                    }else if(i==4){debugger;
                        $this.html( '<input type="text" class="form-control input-block" value="' + data[i] + '"/>' );
                    }else if(i==7){
                        $this.html(statusVal);
                        $row.find("select").eq(1).val(data[8]);//下拉默认选中赋值
                    }else {
                        $this.html( '<input type="text" class="form-control input-block" value="' + data[i] + '"/>' );
                    }
                }
            });

        },

        rowSave: function( $row ) {
            var _self     = this,
                $actions,
                values    = [];

            //删除新增css
            // if ( $row.hasClass( 'adding' ) ) {
            //     this.$addButton.removeAttr( 'disabled' );
            //     $row.removeClass( 'adding' );
            // }
            var select6,status8;
            values = $row.find('td').map(function() {
                var $this = $(this);

                if ( $this.hasClass('actions') ) {
                    _self.rowSetActionsDefault( $row );
                    return _self.datatable.cell( this ).data();
                } else {
                    if($this.index() == 0 ){
                        select6 = $this.find('select').val();
                        return $.trim($this.find('select option:selected').text());
                    }else if($this.index() == 6){
                        return $.trim( select6 );
                    }else if($this.index() == 7){
                        status8 = $this.find('select').val();
                        if(status8 == "0"){
                            return $.trim('<span class="label label-danger">停用</span>');
                        }else {
                            return $.trim('<span class="label label-success">启用</span>');
                        }
                    }else if($this.index() == 8){
                        return $.trim( status8 );
                    }else {
                        return $.trim( $this.find('input').val() );
                    }
                }
            });

            /**
             * 验证信息是否为空
             */
            console.log("select:"+values[0]);
            if(!values[0]){
                checkOut($row,"基础产品不能为空");
                return false;
            }else if(!values[1]){
                checkOut($row,"市场价不能为空");
                return false;
            }else if(isNaN(values[1])){
                checkOut($row,"市场价格式错误");
                return false;
            }else if(!values[4]){
                checkOut($row,"折扣不能为空");
                return false;
            }else if(!values[5]){
                checkOut($row,"通道产品编码不能为空");
                return false;
            }
            /*
             * 参数提交前校验
             */
            function checkOut($row,msg) {
                messageWarn(msg);
                $row.find('a:eq(0)').removeClass("hidden");
                $row.find('a:eq(1)').removeClass("hidden");
                $row.find('a:eq(2)').addClass("hidden");
                $row.find('a:eq(3)').addClass("hidden");
            }

            if ( $row.hasClass( 'adding' ) ) {
                this.$addButton.removeAttr( 'disabled' );
                $row.removeClass( 'adding' );
            }

            this.datatable.row( $row.get(0) ).data( values );
            //新增或修改
            var channelNo = $("#channelNo").val();
            var param={"productid":values[6],"mchid":channelNo,"remark":values[2],"id":values[3],
                "price":values[1],"rebateprice":values[1]*values[4]/100,
                "rebate":values[4],"spuid":values[5],"status":values[8]};
            var result = H5Requset("admin/channelProduct/saveChannelProduct",param,"");
            if(result == "1") {//result为1时操作成功，正常流程
                $actions = $row.find('td.actions');
                if ($actions.get(0)) {
                    this.rowSetActionsDefault($row);
                }

                this.datatable.draw();
            }else {//返回result为2时，产品已存在，进行删除处理，again为一个标识
                _self.rowRemove($row,"again");
            }
        },

        rowRemove: function( $row ,params) {
            if ( $row.hasClass('adding') ) {
                this.$addButton.removeAttr( 'disabled' );
            }
            //start 删除 获取id，根据id删除产品
            var id = $row.find("td").eq(3).text();
            if(params){
                id = "";
            }
            if(!id){
                tables.row( $row.get(0) ).remove().draw();
                return false;
            }
            swal({
                title: "系统提示",
                text: "确定要删除该通道产品吗?",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#FF8247",
                confirmButtonText: "确定删除",
                cancelButtonText: "取消操作",
                closeOnConfirm: false,
                closeOnCancel: true
            }, function (isConfirm) {
                if(isConfirm){
                    H5DelData("get","admin/channelProduct/deleteChannelProduct",{"id":id},"");
                    tables.row( $row.get(0) ).remove().draw();
                }
            });
            //end 删除
        },

        rowSetActionsEditing: function( $row ) {
            $row.find( '.on-editing' ).removeClass( 'hidden' );
            $row.find( '.on-default' ).addClass( 'hidden' );
        },

        rowSetActionsDefault: function( $row ) {
            $row.find( '.on-editing' ).addClass( 'hidden' );
            $row.find( '.on-default' ).removeClass( 'hidden' );
        }

    };

    $(function() {
        EditableTable.initialize();
    });

}).apply( this, [ jQuery ]);